package com.nifostasky.main.dynamicproxy.cglibproxy;


import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibDynamicProxy implements MethodInterceptor {
    /**
     * 目标对象（也被称为被代理对象）
     */
    private Object target;

    public CglibDynamicProxy(Object target) {
        this.target = target;
    }

    /**
     *
     * @param o CGLIB 生成的代理对象
     * @param method 被代理对象方法
     * @param objects 方法入参
     * @param methodProxy 方法代理
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("CglibDynamicProxy intercept 方法执行前-------------------------------");

        System.out.println("obj = " + o.getClass());
        System.out.println("method = " + method);
        System.out.println("proxy = " + methodProxy);

        //代理对象
        Object object = methodProxy.invoke(target, objects);

        System.out.println("CglibDynamicProxy intercept 方法执行后-------------------------------");
        return object;
    }


    /**
     * 获取被代理接口实例对象
     *
     * 通过 enhancer.create 可以获得一个代理对象，它继承了 target.getClass() 类
     *
     * @param <T>
     * @return
     */
    public <T> T getProxy() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return (T) enhancer.create();
    }

}
